package com.origin.netlibrary.interceptor

import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response


/**
 *  多地址切换 拦截器
 *
 *  通过请求头 拦截吧改变 请求主机地址
 */

class MoreBaseUrlInterceptor(private val baseUrl: BaseUrl) : Interceptor {
    companion object {
        const val TAG = "urlName"
    }

    interface BaseUrl {


        fun getBaseUrl(baseUrlTag: String): String

        fun setHeader(builder: Request.Builder) {

        }
    }


    override fun intercept(chain: Interceptor.Chain): Response {
        //获取原始的originalRequest
        val originalRequest = chain.request()
        //获取老的url
        var oldUrl: HttpUrl = originalRequest.url()
        //获取originalRequest的创建者builder
        val builder = originalRequest.newBuilder()
        //获取头信息的集合如：manage,mdffx
        val urlNameList = originalRequest.headers(TAG)
        baseUrl.setHeader(builder)


        //如果添加TAG请求头就是就是其他的网络地址
        if (urlNameList.size > 0 && urlNameList[0] != "download" && urlNameList[0] != "baseUrl") {

            val urlName = urlNameList[0]
            //通过key获取其他请求地址


            oldUrl = if (urlName.isNullOrEmpty()) {
                oldUrl.newBuilder()
                    .build()
            } else {
                val baseHttpUrl = HttpUrl.parse(baseUrl.getBaseUrl(urlName))
                oldUrl.newBuilder()
                    .scheme(baseHttpUrl!!.scheme())//http协议如：http或者https
                    .host(baseHttpUrl.host())//主机地址
                    .port(baseHttpUrl.port())//端口
                    .build()
            }


        }
        val newRequest = builder.url(oldUrl).build()

        return chain.proceed(newRequest)
    }
}